package com.whmskj.xjlhsc.mobie.Scheduling.Service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whmskj.xjlhsc.mobie.Scheduling.Service.LeaveRequestService;
import com.whmskj.xjlhsc.mobie.Scheduling.entity.LeaveRequest;
import com.whmskj.xjlhsc.mobie.Scheduling.mapper.LeaveRequestMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @Author: Sakura
 * @Date: 2025/9/2 11:08
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class LeaveRequestServiceImpl  extends ServiceImpl<LeaveRequestMapper, LeaveRequest>
        implements LeaveRequestService {
    @Override
    public List<LeaveRequest> getLeaveListByCondition(LeaveRequest condition) {
        // 实现根据对象查询的方法
        return baseMapper.selectLeaveListByCondition(condition);
    }

    @Override
    public boolean addLeaveRequest(LeaveRequest leaveRequest) {
        // 计算请假时长
        calculateDuration(leaveRequest);
        leaveRequest.setStatus("pending");
        return this.save(leaveRequest);
    }

    @Override
    public boolean updateLeaveRequest(LeaveRequest leaveRequest) {
        // 计算请假时长
        calculateDuration(leaveRequest);
        return this.updateById(leaveRequest);
    }

    @Override
    public boolean deleteLeaveRequest(Long id) {
        return this.removeById(id);
    }

    /**
     * 计算请假时长
     */
    private void calculateDuration(LeaveRequest leaveRequest) {
        long diffInMillies = Math.abs(leaveRequest.getEndTime().getTime() - leaveRequest.getStartTime().getTime());

        if ("小时".equals(leaveRequest.getLeaveUnit())) {
            // 转换为小时，保留两位小数
            BigDecimal duration = BigDecimal.valueOf(diffInMillies / (1000.0 * 60 * 60));
            leaveRequest.setDuration(duration.setScale(2, RoundingMode.HALF_UP));
        } else {
            // 转换为天，保留两位小数
            BigDecimal duration = BigDecimal.valueOf(diffInMillies / (1000.0 * 60 * 60 * 24));
            leaveRequest.setDuration(duration.setScale(2, RoundingMode.HALF_UP));
        }
    }
}
